package 笔试.美团;

import java.util.Scanner;
import java.util.TreeSet;

//前面小于当前数的最大值
public class Demo03 {
   /* public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] nums = new int[n+1];
        int[] prev = new int[n+1];
        for (int i = 1; i <= n; i++) {
            nums[i] = in.nextInt();
        }
        int res = 0;
        if(nums[1]<nums[2]) prev[2] = nums[1];
        for (int i = 2; i <=n ; i++) {
            int temp = prev[i-1];
            for (int j = 1; j < i; j++) {
                if(nums[j]<nums[i]) temp = Math.max(temp,nums[j]);
            }
            prev[i] = temp;
        }
        for (int i = 1; i <= n; i++) {
            res += prev[i]*i;
        }
        System.out.println(res);

    }*/

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        long sum = 0;
        int[] nums = new int[n];
        for(int i = 0; i < n; i++){
            nums[i] = sc.nextInt();
        }
        int[] prev = new int[n];
        TreeSet<Integer> set = new TreeSet<>();
        for(int i = 0; i < n; i++){
            int temp = nums[i];
            //TreeSet的floor()返回集合中指定元素的等于或最接近的最小元素，如果没有，则返回null。
            Integer top = set.floor(temp);
            if(top == null){
                prev[i] = 0;
            }else{
                if(temp == top){
                    set.remove(temp);
                    Integer nextTmp = set.floor(temp);
                    prev[i] = nextTmp == null ? 0 : nextTmp;
                    set.add(temp); //恢复
                }else{
                    prev[i] = top;
                }
            }
            set.add(temp);
        }
        for(int i = 1; i < n; i++){
            sum += (i + 1) * prev[i];
        }
        System.out.println(sum);
    }

}
